<template>
    <div class="richText">
      <header>{{richTitle}}</header>
      <div class="rt_content">
        <div class="allLevel" v-if="richInedex == 2">
          <div class="titile">请选择问题等级</div>
          <el-dropdown @command="chooseLevel">
            <el-button type="primary" style="border-color: #e5e5e5;width: 191px;height:50px;text-align: left" :style="{color:levelColor,background:'#fff'}">
              {{levelTitle}}<div class="downSJ"></div>
            </el-button>
            <el-dropdown-menu slot="dropdown" style="width: 191px">
              <el-dropdown-item v-for="(item,index) in colorList" :style='{color:item.color}' :command="item" :key="index">{{item.title}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="tips">当问题定义为红色等级，将会启用8D流程解决该问题，在点击确认后，即可进入8D报告的新增页面。</div>
        </div>
        <div class="fileDiv" :style="richInedex == 2?'top:241.5px':'top:41.5px'" @click="clickFile"></div>
        <quill-editor
          v-model="content"
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)"
          @change="onEditorChange($event)">
        </quill-editor>
        <input type="file" ref="uploadFI" name="avatar" id="uploadFI" @change="uploadFiles($event);" accept="image/gif,image/jpeg,image/jpg,image/png" multiple="multiple" class="el-upload__input">
        <input type="file" id="fileId" name="image" class="getImgUrl_file" @change="preview($event)" style="display: none">
      </div>
      <footer>
        <div class="buttons but1" @click="close">取消</div>
        <div class="buttons but2" @click="commitContent">确认</div>
      </footer>
    </div>
</template>

<script>
  import {mapGetters,mapActions} from 'vuex'
  export default {
    props:['richTitle','richInedex','richVal','parLevel'],
    name: "richText",
    data() {
      return {
        content:null,
        editorOption:{// 工具栏配置
          modules:{
            toolbar:[
              ['image', { list: "bullet" }, { list: "ordered" }, { align: [] },'link'],        // toggled buttons

            ],
          }
        },
        colorList:[
          {title:'所有等级',color:'#666666',level:''},
          {title:'红色',color:'#dc4444',level:'1'},
          {title:'橙色',color:'#ff8c1b',level:'2'},
          {title:'黄色',color:'#ffcd34',level:'3'},
          {title:'蓝色',color:'#3384dd',level:'4'}
        ],
        levelTitle:'请选择等级',
        levelColor:'#666666',
        level: '',
        ul:[],
        ul2:[],
      }
    },
    computed:{
      ...mapGetters([
        'showRichText'
      ])
    },
    created() {
    },
    mounted() {
      let self = this
      if (self.richVal != undefined){
        self.content = self.richVal
      }
      if (self.parLevel != undefined && self.parLevel == '1'){
        self.levelTitle = '红色'
        self.levelColor = '#dc4444'
        self.level = '1'
      }
      // 为图片ICON绑定事件 getModule 为编辑器的内部属性
      this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)
    },
    watch:{
      content(val,old){
        let self = this
        if (val.indexOf('null') != -1){
          self.content = val.replace('null','')
        }
      }
    },
    methods: {
      ...mapActions([
        'upstate'
      ]),
      imgHandler (state) {
        this.addRange = this.$refs.myQuillEditor.quill.getSelection()
        if (state) {
          const fileInput = document.getElementById('uploadFI')
          fileInput.click() // 加一个触发事件
        }
      },
      //关闭
      close(){
        let self = this
        self.upstate({key:'showRichText',val:false})
      },
      //内容改变事件
      onEditorChange(even){
        let self = this
        // console.log(even)
      },
      //失去焦点
      onEditorBlur(even){
        let self = this
        let list = even.editor.delta.ops
        for (let i = 0; i < list.length; i++){
          if (list[i].attributes != undefined){
            let newContent = self.content.replace(even.editor.delta.ops[i].attributes.link,'http://' + even.editor.delta.ops[i].attributes.link)
            self.content = newContent
          }
        }
      },
      //获取图片路径
      uploadFiles(event){
        let self = this
        let inputDOM = this.$refs.uploadFI;
        for(var i=0;i<inputDOM.files.length;i++){
          this.ul.push(inputDOM.files[i]);
          let upFile={}
          this.ulNumber++
          upFile["name"]=inputDOM.files[i].name;
          upFile["url"] = window.URL.createObjectURL(inputDOM.files[i]) + '.' + inputDOM.files[i].name.substring(inputDOM.files[i].name.length - 3,inputDOM.files[i].name.length);
          // console.log(upFile,'up')
        }
        this.handFile(inputDOM.files)
      },
      handFile(formData){
        let self = this
        //行动计划
        var data = new FormData();
        for(var i=0;i<formData.length;i++){
          data.append("files", formData[i]);
        }
        self.$http.post(self.conURL + 'mongofileserver/api/upload',data).then(res=>{
          for(var i = 0;i < res.data.length; i++){
            if (self.content != null){
              this.$refs.myQuillEditor.quill.insertEmbed(self.content.length, 'image', localStorage.getItem('imgUrl') +  res.data[i]);
            } else {
              this.$refs.myQuillEditor.quill.insertEmbed(0, 'image', localStorage.getItem('imgUrl') +  res.data[i]);
            }
          }
        }).catch(error=>{
          console.log(error);
        });
      },
      //点击上传文件
      clickFile(){
        let self = this
        const fileInput2 = document.getElementById('fileId')
        fileInput2.click() // 加一个触发事件
      },
      preview(event){
        let self = this
        let inputDOM = document.getElementById('fileId');
        for(var i=0;i<inputDOM.files.length;i++){
          this.ul2.push(inputDOM.files[i]);
          let upFile={}
          this.ulNumber++
          upFile["name"]=inputDOM.files[i].name;
          upFile["url"] = window.URL.createObjectURL(inputDOM.files[i]) + '.' + inputDOM.files[i].name.substring(inputDOM.files[i].name.length - 3,inputDOM.files[i].name.length);
          // console.log(upFile,'up')
        }
        self.getObjectURL(inputDOM.files)
      },
      getObjectURL (formData) {
        let self = this
        // console.log(formData)
        var data = new FormData();
        for(var i=0;i<formData.length;i++){
          data.append("files", formData[i]);
        }
        self.$http.post(self.conURL + 'mongofileserver/api/upload',data).then(res=>{
          for(var i = 0;i < res.data.length; i++){
            let fileType
            let fileName = formData[i].name.substring(0,formData[i].name.length - 4)
            if (formData[i].name.substring(formData[i].name.length - 3,formData[i].name.length) == 'txt'){
              fileType = 'txt'
            }else if (formData[i].name.substring(formData[i].name.length - 3,formData[i].name.length) == 'doc') {
              fileType = 'doc'
            }else if (formData[i].name.substring(formData[i].name.length - 3,formData[i].name.length) == 'pdf') {
              fileType = 'pdf'
            }else if (formData[i].name.substring(formData[i].name.length - 3,formData[i].name.length) == 'ppt') {
              fileType = 'ppt'
            }else if (formData[i].name.substring(formData[i].name.length - 3,formData[i].name.length) == 'xls') {
              fileType = 'xls'
            }else {
              fileType = 'other'
            }
            self.content += '<span><a href="' + localStorage.getItem('imgUrl') + res.data[i] + '" download="' + localStorage.getItem('imgUrl') +  res.data[i] + '">' +
              '<img src="http://120.26.113.44:7080/mongofileserver/image/water/' + fileName + '/' + fileType + '?tdsourcetag=s_pctim_aiomsg"></a></span>'
          }
        }).catch(error=>{
          console.log(error);
        });
      },
      //提交
      commitContent(){
        let self = this
        let par = {
          richInedex:self.richInedex,
          content: self.content
        }
        if (self.level != ''){
          par.level = self.level
        }
        this.$emit('params',par)
        self.upstate({key:'showRichText',val:false})
      },
      //选择等级
      chooseLevel(command){
        let self = this
        self.levelTitle = command.title
        self.levelColor = command.color
        self.level = command.level
      },
    }
  }
</script>

<style lang="less">
  .richText{
    width: 660px;
    height: 100%;
    background: #fff;
    border-left: 1px solid #e5e5e5;
    box-shadow: #eeeeee 0px 0px 15px;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 9;
    header{
      width: 100%;
      height: 74px;
      line-height: 74px;
      border-bottom: 1px solid #e5e5e5;
      padding: 0 30px;
      box-sizing: border-box;
      font-size: 20px;
      color: #222222;
    }
    footer{
      width: 100%;
      height: 59px;
      background: #fafafa;
      border-top: 1px solid #e5e5e5;
      position: absolute;
      right: 0;
      bottom: 0;
      display: flex;
      flex-direction: row;
      justify-content: center;
      .buttons{
        width: 93px;
        height: 37px;
        line-height: 39px;
        text-align: center;
        font-size: 16px;
        margin: auto 0;
        cursor: pointer;
      }
      .but1{
        background: #fff;
        color: #666666;
        border: 1px solid #dddddd;
        margin-right: 10px;
      }
      .but2{
        background: #0f76c8;
        color: #fff;
        border: 1px solid #0f76c8;
      }
    }
    .rt_content{
      display: flex;
      flex-direction: column;
      padding: 30px;
      box-sizing: border-box;
      position: relative;
      .allLevel{
        margin-bottom: 30px;
        border-bottom: 1px dashed #e5e5e5;
        position: relative;
        .titile{
          font-size: 16px;
          color: #666666;
          margin-bottom: 14px;
        }
        .tips{
          margin-top: 16px;
          font-size: 14px;
          color: #999999;
          width: 60%;
          margin-bottom: 30px;
        }
        .downSJ{
          display: inline-block;
          width:0;
          height:0;
          border-left:5px solid transparent;
          border-right:5px solid transparent;
          border-top:7px solid #aaaaaa;
          position: absolute;
          right: 15px;
          top: 22px;
        }
      }
      .fileDiv{
        width: 18px;
        height: 18px;
        position: absolute;
        left: 187px;
        cursor: pointer;
        background: url("../../assets/imgs/file_icon.png");
      }
      .fileDiv:hover{
        background: url("../../assets/imgs/file_icon_houver.png");
      }
    }
  }
</style>
